<template>
  <div class="auto-input-component" style="text-align: left;">
    <string-input v-if="dataType === 'string' || dataType === 'datasource' || dataType === 'foreign' || dataType === ''" v-model.trim="val" :disabled="disabled" @input="onChange" />
    <number-input v-if="dataType === 'number'" v-model.number="val" :disabled="disabled" @input="onChange" />
    <enum-select v-if="dataType === 'enum'" v-model="val" :disabled="disabled" :options="options" @input="onChange" />
    <bool-checkbox v-if="dataType === 'bool'" v-model="val" :disabled="disabled" @input="onChange" />
    <date-input v-if="dataType === 'date'" v-model.trim="val" :disabled="disabled" @input="onChange" />
  </div>
</template>

<script>

export default {
  name: 'AutoInput',
  props: {
    value: {
      type: [String, Number, Boolean, Array],
      default: ''
    },
    dataType: {
      type: String,
      default: 'string'
    },
    options: {
      required: false,
      type: Array,
      default: function() {
        return []
      }
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      val: this.getInitVal(this.value)
    }
  },
  watch: {
    value(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.val = this.getInitVal(newVal)
      }
    },
    dataType(newVal, oldVal) {
      this.val = this.getInitVal(this.value)
    }
  },
  methods: {
    onChange() {
      this.$emit('input', this.val)
    },
    getInitVal(value) {
      if (this.dataType === 'number' || this.dataType === 'date') {
        return Number(value)
      } else if (this.dataType === 'bool') {
        return !!value
      } else {
        return value
      }
    }
  }
}
</script>

<style lang="scss">
  .auto-input-component {
    .el-select {
      width: 100%;
    }
  }
</style>
